'use strict';

const path = require('path')
const Package = require('@sue-cli-dev/package')
const log = require('@sue-cli-dev/log')

const SETTINGS = {
    init: '@sue-cli-dev/init'
}

let pkg

const CACHE_DIR = 'dependencies'

async function exec() {
    // TODO
    let targetPath = process.env.CLI_TARGET_PATH
    const homePath = process.env.CLI_HOME_PATH
    let storeDir = ''
    log.verbose('targetPath', targetPath)
    log.verbose('homePath', homePath)

    const cmdObj = arguments[arguments.length - 1]
    const cmdName = cmdObj.name()
    const packageName = SETTINGS[cmdName]
    const packageVersion = 'latest'

    if (!targetPath) {
        targetPath = path.resolve(homePath, CACHE_DIR)
        storeDir = path.resolve(targetPath, 'node_modules')
        log.verbose('targetPath', targetPath)
        log.verbose('storeDir', storeDir)

        pkg = new Package({
            targetPath,
            storeDir,
            packageName,
            packageVersion,
        })
        if (await pkg.exists()) {
            // 更新package
        } else {
            // 安装package
            await pkg.install()
        }
    } else {
        pkg = new Package({
            targetPath,
            packageName,
            packageVersion,
        })
    }
    const rootFile = pkg.getRootFilePath()
    if (rootFile) {
        require(rootFile).apply(null, arguments)
    }
}

exec()
